/*
 * Copyright (c) 2014. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package CASTest;

import net.rubyeye.xmemcached.CASOperation;
import net.rubyeye.xmemcached.XMemcachedClient;
import org.apache.log4j.xml.DOMConfigurator;

import java.util.concurrent.CountDownLatch;

/**
 * @author 石头哥哥
 *         Date: 13-11-11</br>
 *         Time: 下午2:18</br>
 *         Package: CASTest</br>
 *         注解：
 */
@SuppressWarnings("unchecked")
public class CASThread extends Thread {
    private XMemcachedClient mc;
    private CountDownLatch cd;

    public CASThread(XMemcachedClient mc, CountDownLatch cdl) {
        super();
        this.mc = mc;
        this.cd = cdl;

    }

    public void run() {
        try {
            if (mc.cas("a", 0, new CASOperation() {
                @Override
                public int getMaxTries() {
                    return 100;
                }
                @Override
                public Object getNewValue(long currentCAS, Object currentValue) {
                    System.out.println("currentValue=" + currentValue
                            + ",currentCAS=" + currentCAS);
                    return ((Integer) currentValue).intValue() + 1;
                }
            }))
                this.cd.countDown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class CASTest {
    static int NUM = 100;
    public static void main(String[] args) throws Exception {
        DOMConfigurator.configure("res/log4j.xml");
        XMemcachedClient mc = new XMemcachedClient();
        mc.addServer("127.0.0.1", 11211);
        // 设置初始值为0
        mc.set("a", 0, 0);
        CountDownLatch cdl = new CountDownLatch(NUM);
        // 开NUM个线程递增变量a
        for (int i = 0; i < NUM; i++)
            new CASThread(mc, cdl).start();
        cdl.await();
        // 打印结果,最后结果应该为NUM
        System.out.println("result=" + mc.get("a"));
        mc.shutdown();
    }
}
